﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebInstagram.DAL;
using WebInstagram.Models;
using WebInstagram.ViewModels;

namespace WebInstagram.API
{
    public class LikesController : ApiController
    {
        private Context db = new Context();
        LikesRepository rep = new LikesRepository();
        // GET: api/Likes
        public IEnumerable<LikeView> GetPhotoLikes(int ID)
        {
            var likes = rep.GetPhotoLikes(ID);

            var viewLikes = new List<LikeView>();
            Mapper.CreateMap<Like, LikeView>();
            foreach (var like in likes)
            {
                var view = new LikeView();
                view = Mapper.Map<Like, LikeView>(like, view);
                viewLikes.Add(view);
            }

            return viewLikes;
        }


        // POST: api/Likes
        [ResponseType(typeof(Like))]
        public IHttpActionResult PostLike(Like like)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Likes.Add(like);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = like.Id }, like);
        }

        // DELETE: api/Likes/5
        [ResponseType(typeof(LikeView))]
        public IHttpActionResult DeleteLike(int ID)
        {
            if (ID == 0)
            {
                return NotFound();
            }

            var like = db.Likes.Where(l => l.Id == ID).FirstOrDefault();
            if (like == null)
            {
                return NotFound();
            }

            db.Likes.Remove(like);
            db.SaveChanges();

            return Ok(like);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool LikeExists(int id)
        {
            return db.Likes.Count(e => e.Id == id) > 0;
        }
    }
}